package com.company.example.controller;

import com.company.example.core.util.StringUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.UUID;

/**
 * Created by ywl on 2016/12/15.
 */
@Controller
@RequestMapping("/common")
public class CommonController {
    private final static String DIR = "/upload";

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(HttpServletRequest request) throws IOException{
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("filename");
        if(file != null && !file.isEmpty()) {
            float fileSize = Float.valueOf(file.getSize());// 返回文件大小，单位为k
            String extend = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
            String saveFileName = UUID.randomUUID().toString() + "." + extend;
            String saveFilePathName = request.getServletContext().getRealPath("/") + DIR;
            File path = new File(saveFilePathName);
            if(!path.exists()) {
                path.mkdir();
            }
            String filePath = saveFilePathName + File.separator + saveFileName;
            System.out.println("filePath:"+filePath);
            DataOutputStream out = new DataOutputStream(new FileOutputStream(filePath));
            InputStream is = null;
            try {
                is = file.getInputStream();
                int size = (int)fileSize;
                byte[] buffer = new byte[size];
                while(is.read(buffer) > 0) {
                    out.write(buffer);
                }
            }catch(IOException e) {
                e.printStackTrace();
            }finally {
                if(is != null) {
                    is.close();
                }
                if(out != null) {
                    out.close();
                }
            }
            return DIR + "/" + saveFileName;
        }
        return null;
    }

    @RequestMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            String ewm = request.getParameter("filename");
            String proName = StringUtil.isEmpty(request.getContextPath()) ? "" : request.getContextPath();
            String reqRootUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + proName;
            System.out.println("reqRootUrl:"+reqRootUrl);
            String fileName =  reqRootUrl + ewm;
            System.out.println("fileName:"+fileName);
            //处理中文乱码
            request.setCharacterEncoding("UTF-8");
            fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8");
            //处理浏览器兼容
            response.setContentType("application/msexcel;charset=utf-8");//定义输出类型
            Enumeration enumeration = request.getHeaders("User-Agent");
            String browserName = (String) enumeration.nextElement();
            String fileRealName = ewm.replace("/upload/","");
            boolean isMSIE = browserName.contains("MSIE");
            if (isMSIE) {
                response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileRealName, "UTF8"));
            } else {
                response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileRealName.getBytes("gb2312"), "ISO8859-1"));
            }
            //url地址如果存在空格，会导致报错！  解决方法为：用+或者%20代替url参数中的空格。
            fileName = fileName.replace(" ", "%20");
            //图片下载
            URL url = new URL(fileName);
            URLConnection conn = url.openConnection();
            outputStream = response.getOutputStream();
            inputStream = conn.getInputStream();
            IOUtils.copy(inputStream, outputStream);
        } catch (IOException e) {
            System.err.println(e);
        }finally {
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(outputStream);
        }
    }
}
